const http = require('http');
const fs = require('fs');
const path = require('path');

let getMsg = function({ success = true, msg = '', data = null }) {
    return JSON.stringify(
        {
            success,
            msg,
            data
        }
    )
}

const server = http.createServer((req, res) => {
    // 静态资源处理
    if (/.(html|js)$/.test(req.url)) {
        let filePath = path.join(__dirname, req.url)
        if (fs.existsSync(filePath)) {
            res.writeHead(200);
            fs.createReadStream(filePath).pipe(res)
        } else {
            res.statusCode = 404
            res.end('404')
        }
    } else {
        // login
        if (req.method === 'POST') {
            res.statusCode = 200
            res.setHeader('Content-Type', 'application/json; charset=utf-8')
            // login  登录
            if (req.url.startsWith('/login')) {
                setTimeout(function() {
                    res.end(getMsg({
                        data: {
                            name: '石兴龙',
                            id: '001'
                        }
                    }))
                }, 1000)
            } else if (req.url.startsWith('/getVipInfo')) {
                // getVipInfo 查询用户会员
                setTimeout(function() {
                    res.end(getMsg({
                        data: {
                            isVip: true,
                            endDay: '2020-9-24 24:00:00'
                        }
                    }))
                }, 900)
            } else if (req.url.startsWith('/isRemind')) {
                // isRemind 是否要提醒用户会员快要到期
                setTimeout(function() {
                    res.end(getMsg({
                        data: {
                            isRemind: true
                        }
                    }))
                }, 100)
            }
        }
    }
})

server.listen(3001, () => {
    console.log('server is runing localhost:3001')
})
